import { observable, action, runInAction } from 'mobx'
import { post } from 'lib/net'
import CommonVM from 'cvm/common'
import * as api from 'lib/constants/api'
import lrz from 'lrz'
import Toast from 'components/toast'

export default class UserInfomationVM extends CommonVM {
  constructor (props) {
    super()
    this.props = props
    this.fetchData()
  }
  // 个人中心数据
  @observable data = null
  // 姓名
  @observable nameValue = ''
  // 修改姓名Dialog
  @observable visibleName = false
  // 加载
  @observable loading = false

  // 获取个人中心数据
  @action fetchData = async () => {
    let params = {ID: this.userId}
    Toast.loading()
    let res = await post(api.USER_INFO, params)
    if (res.state === 1) {
      runInAction(() => {
        this.data = res.data
      })
      Toast.loading(2)
    } else {
      Toast.offline('网络异常')
    }
  }

  // 压缩图片
  @action compressImage = file => {
    Toast.loading(1, '正在压缩')
    lrz(file, {width: 800})
    .then(rst => {
      this.updateImage({Base64: rst.base64, ImageName: file.name})
    }).catch(() => {
      this.loading = false
      Toast.fail('压缩失败')
    })
  }

  // 上传图片
  updateImage = async params => {
    Toast.loading(1, '正在上传')
    let res = await post(api.IMAGE_UPLOAD64, params)
    if (res.state === 1) {
      this.updateIcon(res.data, params.Base64)
    } else {
      Toast.fail('上传失败')
    }
  }

  // 上传头像路径
  @action updateIcon = async (url, base64) => {
    let params = {ID: this.userId, Headimgurl: url}
    let res = await post(api.UPDATE_ICON, params)
    if (res.state === 1) {
      this.data.Headimgurl = base64
      Toast.success('修改成功')
    } else {
      Toast.fail('上传失败')
    }
  }

  // 修改头像
  @action handleImageChange = e => {
    let file = e.target.files[0]
    if (file && file.size <= 0) return
    this.compressImage(file)
    e.target.value = ''
  }

  // 修改姓名
  @action handleChangeName = e => {
    this.nameValue = e.target.value
  }

  // 显示姓名Dialog
  @action handleShowNameDialog = () => {
    this.visibleName = true
  }

  // 确认修改姓名
  @action handleOkName = async () => {
    if (this.nameValue.length === 0) return
    let params = {ID: this.userId, Nickname: this.nameValue}
    this.data.Nickname = this.nameValue
    this.handleCancelNameDialog()
    post(api.UPDATE_NICKNAME, params)
  }

  // 取消姓名修改
  @action handleCancelNameDialog = () => {
    this.visibleName = false
  }

  // 性别修改
  @action handleSexChange = value => {
    this.data.Sex = value
    let params = {ID: this.userId, Sex: value}
    post(api.UPDATE_SEX, params)
  }
}
